<template>
  <div class="pay-zb-container">
    <div class="pay-zb-header">
      <div class="header-left">
        <div class="user-head">
          <img :src="avatar" class="user-avatar"/>
          <svg-icon :icon-class="userInfo.is_member?'vip':'uvip'" className="vip-icon"/>
        </div>
        <div class="info-wrap">
          <p class="user-name">{{userInfo.Nickname || '未登录'}}</p>
          <p class="zb-info">
            <span class="c-orange mr10"><svg-icon iconClass="zb" className="zb-icon"></svg-icon>智币：{{ userZbNum }}</span>
            <span class="receive-zb" v-if="canReceiveZb" @click="receiveZb">免费领</span>
          </p>
        </div>
      </div>
      <span v-if="hasLogin" class="logout-btn" @click="handleLoginOut">退出登录</span>
      <span v-else class="unlogin-head-btn" @click="handleLogin">立即登录</span>
    </div>
    <div class="pay-zb-content">
      <div class="product-box">
        <div v-for="item in products"
          :key="item.id"
          class="product-item"
          :class="{active:selectedProduct.id===item.id}"
          @click="setProductItem(item)">
          <div v-if="item.discount!==10" class="discount-tips"><div class="hot-tips">{{item.discount}}折</div></div>
          <div v-if="item.discount===10 && item.give" class="discount-tips"><div class="hot-tips">赠送</div></div>
          <div class="zb-number">
            <svg-icon iconClass="zb" class="zb-icon"/>
            <span>{{item.num}}</span>
            <span v-if="item.give" class="give-num">+{{item.give}}</span>
          </div>
          <div class="money-price">￥{{item.price|moneyToyuan}}</div>
        </div>
        <div class="product-custom mt30"
          v-if="enableCustom">
          <div class="custom-header">
            <div class="custom-title">自定义</div>
            <div>￥1={{exchangeRate}}智币</div>
          </div>
          <div class="custom-content mt10" :class="{active:selectedProduct.id===-1000}">
            <el-input v-model="input"
              ref="customInput"
              maxlength="6"
              class="custom-input"
              :placeholder="`请输入金额（最低￥${leastPayAmount}）`"
              @input="onCustomInput"
              @blur="customInputBlur"/>
            <span v-if="customNumInfo.price" class="custom-zb">共计{{customNumInfo.price*exchangeRate}}<span v-if="customNumInfo.give">+{{customNumInfo.give}}(赠送)</span>币</span>
          </div>
        </div>
      </div>
      <div class="pay-box">
        <p class="text-center">请使用微信或支付宝扫码完成支付</p>
        <PaymentCode :product="zbProduct"
          v-if="isXzMerchant"
          :otherParamsStr = "otherParamsStr"
          :hasLogin="hasLogin"
          class="pay-code"
          @login="handleLogin"
          @onStatusChange="onStatusChange"/>
        <LyPaymentCode v-else
          :product="zbProduct"
          class="pay-code"
          :otherParamsStr="otherParamsStr"
          :hasLogin="hasLogin"
          @login="handleLogin"
          @onStatusChange="onStatusChange"/>
        <div class="mt15 text-center">
          <p class="pay-price color-warn">￥<span>{{selectedProduct.payPrice|valToFixed2}}</span></p>
          <p class="fs12" v-show="selectedProduct.discountPrice">已优惠￥{{ selectedProduct.discountPrice|valToFixed2 }}</p>
        </div>
        <span class="agreement" @click="openUrl">《智币购买协议》</span>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import Axios from 'axios'
import PaymentCode from '@/components/payment-code'
import LyPaymentCode from '@/components/payment-code/src/ly-payment-code'
import { getZbSetting, getZbProduct, getUserZbApi, getGiftOpt, drawGiftOpt } from '@/api/zb'

export default {
  name: 'PayZB',
  components: {
    PaymentCode,
    LyPaymentCode
  },
  data () {
    return {
      userZbNum: 0,
      canReceiveZb: false,
      zbProduct: {},
      exchangeRate: 0,
      leastPayAmount: 1,
      enableCustom: true,
      giveOptions: [],
      discountRateOptions: [],
      selectedProduct: {},
      customNumInfo: {
        id: -1000,
        price: '',
        num: 0,
        discount: 10,
        give: 0,
        discountPrice: 0,
        payPrice: 0
      },
      products: []
      // otherParamsStr: '{}'
    }
  },
  watch: {
    hasLogin () {
      this.initUserInfo()
    }
  },
  computed: {
    ...mapGetters(['appInfo', 'appCfg', 'userInfo', 'hasLogin']),
    isXzMerchant () {
      return this.appInfo.merchant === 'xz'
    },
    avatar () {
      return this.userInfo?.Portrait || require('@/assets/avatar.svg')
    },
    input: {
      get () {
        if (this.customNumInfo.price.length) {
          return '￥' + this.customNumInfo.price
        } else {
          return ''
        }
      },
      set (val) {
        val = val.replace(/\b(0+)|[^\d]/g, '')
        this.customNumInfo.price = val
      }
    },
    otherParamsStr () {
      const params = {
        act_fixed_id: '9999'
      }
      params.quantity = this.selectedProduct.num
      return JSON.stringify(params)
    }
  },
  filters: {
    moneyToyuan (val = 0) {
      return parseFloat((val / 100).toFixed(2))
    },
    valToFixed2 (val = 0) {
      return (val / 100).toFixed(2)
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.meta.whiteList || this.userInfo.user_id) {
      next()
    } else {
      this.handleLogin()
      next(false)
    }
  },
  created () {
    this.initUserInfo()
    Axios.all([getZbProduct({ product_type: 3 }), getZbSetting({ key: ['pay_amount', 'pay_discount'] })]).then(Axios.spread((res1, res2) => {
      const data1 = res1.data || {}
      const data2 = res2.data.data || {}
      const payDiscount = data2.pay_discount || {}
      const payAmount = data2.pay_amount || {}
      this.zbProduct = data1
      this.exchangeRate = parseInt(100 / data1.price)
      this.leastPayAmount = this.formatMoney(payAmount.least_pay_amount) || 1
      this.enableCustom = payAmount.enable_custom_pay_amount
      if (payDiscount.enable_pay_discount_give) {
        this.giveOptions = payDiscount.pay_discount_give_opt || []
      }
      if (payDiscount.enable_pay_discount_rate) {
        this.discountRateOptions = payDiscount.pay_discount_rate_opt || []
      }
      this.products = (payAmount.quick_pay_amount_opt || []).map(item => {
        const obj = {
          id: item,
          price: item,
          num: this.exchangeRate * item / 100
        }
        const discountObj = this.getDiscountFn(item)
        const discount = discountObj.discount
        const discountPrice = item * ((10 - discount) / 10)
        obj.discount = discount
        obj.give = discountObj.give
        obj.payPrice = item - discountPrice
        obj.discountPrice = discountPrice
        return obj
      })
      this.setProductItem(this.products[0] || {})
    }))
  },
  methods: {
    initUserInfo () {
      if (!this.hasLogin) {
        this.canReceiveZb = false
        this.userZbNum = 0
      } else {
        this.getUserZbInfo()
        getGiftOpt().then(res => {
          const data = res.data || {}
          this.canReceiveZb = data.enable && !data.has_draw && data.num > 0
        })
      }
    },
    getUserZbInfo () {
      getUserZbApi().then(res => {
        this.userZbNum = res.data.amount || 0
      })
    },
    /** 退出登录 */
    handleLoginOut () {
      this.$xz('xz_set_stat_id', 0)
      this.$store.dispatch('user/logout')
    },
    handleLogin () {
      this.$store.dispatch('user/login')
    },
    receiveZb () {
      if (this.receiveZbLoading) return
      this.receiveZbLoading = true
      drawGiftOpt().then(() => {
        this.getUserZbInfo()
        this.canReceiveZb = false
        this.$PsMessage({ message: '领取成功' })
      }).finally(() => {
        this.receiveZbLoading = false
      })
    },
    onCustomNumClick () {
      this.$xz('xz_substat_action', 2284)
      this.selectedProduct = this.customNumInfo
      this.$refs.customInput.focus()
    },
    openUrl () {
      this.$xz('xz_open_url', `${this.appCfg.site}/zb-protocol.html`)
    },
    getDiscountFn (item) {
      const giveObj = this.giveOptions.find(itema => itema.start <= item && itema.stop >= item) || {}
      const discountObj = this.discountRateOptions.find(itema => itema.start <= item && itema.stop >= item) || {}
      return {
        discount: (discountObj.discount || 100) / 10,
        give: giveObj.discount
      }
    },
    formatMoney (money = 0) {
      return parseFloat((money / 100 || 0).toFixed(2))
    },
    setProductItem (item) {
      this.$xz('xz_substat_action', 2283)
      this.selectedProduct = item
    },
    onCustomInput () {
      const price = this.customNumInfo.price * 100 || 0
      const discountObj = this.getDiscountFn(price)
      this.customNumInfo.give = discountObj.give
    },
    customInputBlur () {
      if (this.customNumInfo.price >= this.leastPayAmount) {
        const price = this.customNumInfo.price * 100 || 0
        const discountObj = this.getDiscountFn(price)
        const discount = discountObj.discount
        const discountPrice = price * ((10 - discount) / 10)
        this.customNumInfo.discount = discount
        this.customNumInfo.num = price * this.exchangeRate / 100
        this.customNumInfo.discountPrice = discountPrice
        this.customNumInfo.payPrice = price - discountPrice
        this.selectedProduct = this.customNumInfo
      }
    },
    onStatusChange (status) {
      if (status !== 'succes') return
      this.getUserZbInfo()
      this.$PsMessage({ message: '充值成功' })
      this.$xz('xz_update_pay_zb_result', true)
    }
  }
}
</script>

<style lang="scss" scoped>
.pay-zb-container {
  width: 100%;
  height: 100%;
  padding: 16px 20px;
  font-size: 14px;
  border-radius: 6px;
}
.pay-zb-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 13px 20px;
  background: rgba(255,255,255,0.05);
  border-radius: 10px;
  .header-left{
    display: flex;
    align-items: center;
  }
  .user-name{
    margin-bottom: 5px;
    color: #fff;
  }
  .zb-info{
    font-size: 12px;
    .zb-icon{
      margin-right: 5px;
      margin-bottom: -1px;
      font-size: 16px;
    }
    .receive-zb{
      color: #00CCE9;
      cursor: pointer;
      &:hover{
        text-decoration: underline;
      }
    }
  }
  .user-head{
    position: relative;
    margin-right: 10px;
    .user-avatar{
      width: 50px;
      height: 50px;
      border-radius: 50%;
    }
    .vip-icon{
      position: absolute;
      top: -2px;
      right: -8px;
      font-size: 24px;
    }
  }
  .logout-btn{
    font-size: 12px;
    cursor: pointer;
    &:hover{
      color: #fff;
    }
  }
  .unlogin-head-btn{
      margin-left: 20px;
      padding: 4px 21px;
      background: #00B8E6;
      border-radius: 4px;
      font-size: 12px;
      color: #fff;
      cursor: pointer;
      &:hover {
        background: #00A9D3;
      }
    }
}
.c-orange{
  color: #F8DE9D;
}
.pay-zb-content{
  display: flex;
  margin-top: 18px;
  .product-box{
    flex: 0 0 250px;
    width: 250px;
  }
  .product-item{
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 56px;
    padding: 20px 40px 20px 20px;
    background-image: url('~@/assets/pay-zb.png');
    background-repeat: no-repeat;
    background-position: 0 0;
    background-size: 100%;
    color: #D6B383;
    cursor: pointer;
    &+.product-item{
      margin-top: 10px;
    }
    &:hover{
      background-image: url('~@/assets/pay-zb-h.png');
    }
    &.active{
      color: #7B4801;
      background-image: url('~@/assets/pay-zb-a.png');
    }
    .zb-icon{
      margin-right: 5px;
      font-size: 20px;
    }
    .zb-number,.money-price{
      font-size: 16px;
      font-weight: bold;
    }
    .give-num{
      font-size: 12px;
      font-weight: 400;
    }
  }
}
.discount-tips{
  position: absolute;
  z-index: 1;
  right: -3px;
  top: -3px;
  width: 54px;
  height: 54px;
  background: url('../../assets/hot.png');
  text-align: center;
  font-size: 12px;
  color: #fff;
  .hot-tips{
    position: relative;
    bottom: -10px;
    left: 10px;
    font-size: 12px;
    font-weight: bold;
    color: #fff;
    text-align: center;
    transform: rotate(45deg);
  }
}
.custom-header{
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  .custom-title{
    color: #fff;
    font-weight: bold;
  }
}
.custom-content{
  position: relative;
  .custom-zb{
    position: absolute;
    right: 10px;
    top: 12px;
    font-size: 12px;
  }
}
.pay-box{
  flex: 1;
  position: relative;
  margin-left: 18px;
  padding-top: 20px;
  height: 286px;
  background: rgba(255,255,255,0.03);
  border-radius: 10px;
  .pay-code{
    margin: 15px auto 0;
    border-radius: 5px;
    overflow: hidden;
  }
  .pay-price{
    margin-bottom: 8px;
    span{
      font-weight: bold;
      font-size: 20px;
    }
  }
}
.agreement{
  position: absolute;
  right: 0;
  bottom: -30px;
  font-size: 12px;
  cursor: pointer;
  &:hover{
    color: #fff;
  }
}
</style>
<style lang="scss">
.custom-input{
  .el-input__inner{
    width: 250px;
    padding-left: 15px;
    background-color: rgba(0,0,0,0.3);
    border: 1px solid rgba(255,255,255,0.2);
    font-size: 14px;
    color: #fff;
    font-weight: bold;
    &::placeholder{
      color: rgba(255,255,255,0.5);
      font-size: 14px;
      font-weight: 400;
    }
    &:focus{
      border-color: #00CCE9;
    }
  }
}
.active{
  .custom-input{
    .el-input__inner{
      border-color: #00CCE9;
    }
  }
}
</style>
